package Sort;

import java.util.Arrays;

public class CountSort {
    public static void countSort(int[] array){
        int minNum = array[0];
        int maxNum =array[0];
        //找到最大和最小值
        for (int i = 0; i < array.length; i++) {
            if(array[i]>maxNum){
                maxNum = array[i];
            }
            if(array[i]<minNum){
                minNum = array[i];
            }
        }

        int[] count  = new int[maxNum-minNum+1];
        //遍历array数组进行计数
        for (int i = 0; i < array.length; i++) {
            count[array[i]-minNum]++;
        }

        //遍历count
        int index = 0;//指向array的下标
        for (int i = 0; i < count.length; i++) {
            //count内的数取完
            while(count[i]>0){
                array[index] = i+minNum;
                index++;
                count[i]--;
            }
        }
    }


    public static void main(String[] args) {
        int[] array ={2,54,12,1,11,65,4};
        countSort(array);
        System.out.println(Arrays.toString(array));
    }
}
